"use strict";
window.onload = function() {
  var vm = new Vue({
    el: "#view",
    data: {
      // sortList:[
      //   {
      //     id: "1",
      //     name: "单价升序"
      //   },
      //   {
      //     id: "0",
      //     name: "单价降序"
      //   },
      //   {
      //     id: "6",
      //     name: "最新"
      //   }
      // ],
      sortList:[
        {id: "0",name: "高单价优先"},
        {id: "1",name: "低单价优先"},
        // {id: "3",name: "高层建筑优先"},
        // {id: "4",name: "低层建筑优先"},
        // {id: "5",name: "新建建筑优先"},
        // {id: "6",name: "非新建建筑优先"},
        // {id: "7",name: "面积大优先"},
        // {id: "8",name: "面积小优先"},
        {id: "6",name: "最新优先"}
      ],
      tradingareas: [
        { item_id: "500", item_name: "500米",distance_name:'500米'},
        { item_id: "1000", item_name: "1000米",distance_name:'1000米' },
        { item_id: "2000", item_name: "2000米",distance_name:'2000米' },
        { item_id: "5000", item_name: "5000米",distance_name:'5000米' }
      ],
      priceList: [
        {
          id: "1",
          name: "0～4元/m²·天",
          min: "0",
          max: "4"
        },
        {
          id: "2",
          name: "5～6元/m²·天",
          min: "5",
          max: "6"
        },
        {
          id: "3",
          name: "7～10元/m²·天",
          min: "7",
          max: "10"
        },
        {
          id: "4",
          name: "11～14元/m²·天",
          min: "11",
          max: "14"
        },
        {
          id: "5",
          name: "15元/m²·天以上",
          min: "15",
          max: ""
        }
      ],
      areaLists: [
        {
          id: "1",
          name: "0～100m²",
          min: "0",
          max: "100"
        },
        {
          id: "2",
          name: "100～300m²",
          min: "100",
          max: "300"
        },
        {
          id: "3",
          name: "300～500m²",
          min: "300",
          max: "500"
        },
        {
          id: "4",
          name: "500～1000m²",
          min: "500",
          max: "1000"
        },
        {
          id: "5",
          name: "1000m²以上",
          min: "1000",
          max: "-1"
        }
      ],
      decorateLists: [
        {
          id: "1",
          name: "毛坯"
        },
        {
          id: "2",
          name: "标配简装"
        },
        {
          id: " 3",
          name: "遗留装修"
        },
        {
          id: "4",
          name: "拎包入住(装修家具)"
        }
      ],
      floor: [
        {
          id: "1",
          name: "低层(1~7)",
          max: "7",
          min: "1"
        },
        {
          id: "2",
          name: "中层(8~15)",
          max: "15",
          min: "8"
        },
        {
          id: "3",
          name: "高层(16~30)",
          max: "30",
          min: "16"
        },
        {
          id: "4",
          name: "超高层(30以上)",
          max: "-1",
          min: "30"
        }
      ],
      toward: [
        {
          id: "0",
          name: "东"
        },
        {
          id: "1",
          name: "南"
        },
        {
          id: "2",
          name: "西"
        },
        {
          id: "3",
          name: "北"
        }
      ],
      theissuer: [
        {
          id: "0",
          name: "个人业主"
        },
        {
          id: "1",
          name: "开发商"
        },
        {
          id: "2",
          name: "资产管理公司"
        },
        {
          id: "3",
          name: "中介公司"
        }
      ],
      propertyList: [
        {
          id: "1",
          name: "国企"
        },
        {
          id: "2",
          name: "私企"
        },
        {
          id: "5",
          name: "合资"
        },
        {
          id: "3",
          name: "港澳台资"
        },
        {
          id: "4",
          name: "外资"
        }
      ],
      type: [
        {
          id: "1",
          name: "园区"
        },
        {
          id: "0",
          name: "写字楼"
        }
      ],
      gardenType: [
        {
          id: "1",
          name: "文创"
        },
        {
          id: "2",
          name: "科技"
        },
        {
          id: "3",
          name: "其他"
        }
      ],
      areaList: [],     
      linesList:[],
      linesbusList: [],
      businessList: [],
      linesList: [],
      selectBar:{
        area:'区域',
        subway:'地铁',
        sort:'排序'
      },
      query: {
        distance:0,
        townId: "",
        tradingAreaId: "",
        subwayLineId: "",
        subwayStationId: "",
        sort: "",
        gardenFlag: "",
        gardenType: "",
        priceMax: "9999",
        priceMin: "",
        areaMax: "9999",
        areaMin: "",
        fitmentStatus: "",
        floorNoMax: "9999",
        floorNoMin: "",
        managementType: "",
        pubulishCompany: "",
        labelId: "",
        keywords: "",
        page: "1",
        size: "10"
      },
      buildingList:[],
      buildingListIds:[],
      total:0,
      attentionTypeNum:[],
      countVisitNum:[],
      more:true,
      totalNum:0        
    },
    created: function() {
      if (this.getCookie("signature")) {
        this.token = this.getCookie("signature");
      }
      if (this.IEVersion() !== -1) {
        var kword = decodeURI(this.getParams("keyword"));
      } else {
        var kword = decodeURI(escape(this.getParams("keyword")));
      }
      this.query.keywords = kword;
      this.getCommonCityItems();
      this.searchBuildingPage();
    },
    methods: {
      //搜索获取列表
      searchBuildingPage: function(more) {
        var $this = this;
        this.buildingList = more ? this.buildingList : [];
        this.buildingListIds = more ? this.buildingListIds : [];
        //为了把<热门商圈>和<附近>的active状态留住，在这用临时变量接一下，过滤掉非法的townId值
        let query1 = JSON.parse(JSON.stringify(this.query));
        if((query1.townId == 'distance')||(query1.townId == 'hot')){
          query1.townId="";
        }
        house_server.searchBuildingPage(query1, function(res) {
          if (res.code == 200) {
            $this.total = res.data.total;
            if(res.data.list.length>0){
              res.data.list.forEach(function (item) {
                $this.buildingList.push(item);
                $this.buildingListIds.push(item.buildingId);
              });
              $this.getCountVisits($this.buildingListIds);
              $this.getAttentionTypeNums($this.buildingListIds);
            }
            if($this.query.page ==1){
              $this.more = res.data.total>$this.query.size;
              $this.totalNum = res.data.total;
            }
          }
        });
        $(".third-info").hide();
        $(".all-list").show(100);
      },   
      search(){
        this.query.page = 1;
        this.searchBuildingPage('');
      },
      //统计关注人数  
      getAttentionTypeNums: function(ids) {
        var $this = this;
        house_server.getAttentionTypeNums({ids: ids,type: 1},
          function(data) {
            $this.attentionTypeNum = [];
            data.data.forEach(function(item) {
              $this.attentionTypeNum.push(item.count);
            });
          }
        );
      },
       //获取浏览量（多）
       getCountVisits: function(ids) {
        var $this = this;
        this.countVisitsList = [];
        house_server.getCountVisits(
          {
            ids: ids,
            type: 1
          },
          function(data) {
            $this.countVisitNum = [];
            data.data.forEach(function(item) {
              $this.countVisitNum.push(item.count);
            });
          }
        );
      },    
      loadMore(){
        this.query.page++;
        this.searchBuildingPage(1);
        if(this.query.page>=(this.totalNum / this.query.size)){
          this.more = false ;
        }
      },  
      // 跳转详情页
      // goDetail: function(list) {
      //   window.location.href =
      //     "../community/community.html?id=" + list.communityId;
      // },
      goDetail(item){
        window.open("/three/loupan.html?name=" + item.building3dCode + "&cnt=0&buildid=" + item.buildingId)
      },
      // 根据城市id获取区县
      getCommonCityItems: function() {
        var $this = this;
        house_server.getCommonCityItems({cityId: "1"}, function(res) {
            if (res.code == 200) {
              var params = res.data.params[0];
              //为区域和地铁线下一级列表加全部选项             
              let areaList = params.towns; // 区域
              areaList.unshift({item_id:'',item_name:'全部',tradingareas:[]});//区域加全部 
              areaList.forEach(item=>{
                item.tradingareas.unshift({item_id:item.item_id,item_name:'全部',parent_name:item.item_name})
              })
              $this.areaList = areaList;   
              $this.getHotTradingArea();  
              $this.getArea(areaList[0]);         
              let linesList = params.lines; //地铁线
              let lineAllObj = {item_id:'',item_name:'全部',stations:[]};//地铁线加全部
              linesList.unshift(lineAllObj);
              linesList.forEach(item=>{
                item.stations.unshift({item_id:item.item_id,item_name:'全部',parent_name:item.item_name})
              })
              $this.linesList = linesList;
              $this.getlines(linesList[0]);
            }
          }
        );
      },
      // 区域
      getHotTradingArea: function() {
        var _this = this;
        house_server.getHotTradingArea({}, function(res) {
          res.data.forEach(function(element) {
            element.item_name = element.tradingArea;
            element.item_id = element.tradingAreaId;
          });
          _this.areaList.splice(1,0,
              {item_id: "distance",item_name: "附近",tradingareas: _this.tradingareas},
              {item_id: "hot",item_name: "热门商圈",tradingareas: res.data});
        });
      },
       //获取商圈
       getArea: function(area) {
        this.query.townId = area.item_id;
        this.businessList = area.tradingareas; 
      },
      // 点击商圈
      getbus(business){
        if('tradingAreaId' in business){//点击热门商圈
            this.query.distance="";
            this.query.townId='hot';
            this.query.tradingAreaId = business.item_id;
            this.selectBar.area = this.query.tradingAreaId==''?'区域':business.item_name;
        }else if('distance_name' in business){//点击附近
            this.query.townId='distance';
            this.query.tradingAreaId = "";
            this.query.distance = business.item_id;
            this.selectBar.area = this.query.distance==''?'区域':business.item_name;
        }else{//点击正常区域
            this.query.distance="";
            this.query.tradingAreaId='';
            if(business.item_name == '全部'){
                this.query.townId = business.item_id;
                this.selectBar.area = this.query.townId==''?'区域':business.parent_name; //把选中的值放到筛选头上
            }else{
                this.query.tradingAreaId = business.item_id;
                this.selectBar.area = this.query.tradingAreaId==''?'区域':business.item_name;
            }
        }
        this.query.page = 1;
        this.searchBuildingPage();
        $(".third-info").hide();
        $(".all-list").show(100);
      },
      //地铁线
      getlines: function(lines) {
        this.query.subwayLineId = lines.item_id;
        this.linesbusList = lines.stations;
      },
      getlibus: function(libus) {
        this.query.subwayStationId ='';
        if(libus.item_name == '全部'){
          this.query.subwayLineId = libus.item_id;
          this.selectBar.subway = this.query.subwayLineId==''?'地铁':libus.parent_name; //把选中的值放到筛选头上
        }else{
          this.query.subwayStationId = libus.item_id;
          this.selectBar.subway = this.query.subwayStationId==''?'地铁':libus.item_name;
        }
        this.query.page = 1;
        this.searchBuildingPage();
        $(".third-info").hide();
        $(".all-list").show(100);
      },
      //排序
      sort(item){
        this.query.page = 1;
        // console.log(item)
        this.query.sort = this.query.sort==item.id?'':item.id;//0-升 1-降
        this.selectBar.sort = this.query.sort==''?'排序':item.name;
        // console.log(this.query);
        this.searchBuildingPage();
      },
      //处理筛选项
      handleChooseSelect(type,param){
        switch(type){
          case 'type':
            this.query.gardenFlag  = this.query.gardenFlag  == param.id?'':param.id;
            this.query.gardenType = '';//切换类型时联动项清空
            break;
          case 'gardenType':
            this.query.gardenType  = this.query.gardenType  == param.id?'':param.id;
            break;
          case 'price':  
            if(this.query.priceMin == param.min){
              this.query.priceMax  = "9999";  
              this.query.priceMin  = "";  
            }else{
              this.query.priceMax  = param.max;  
              this.query.priceMin  = param.min;
            }
            break;
          case 'property':
              this.query.managementType = this.query.managementType == param.id?'':param.id;
              break;           
        }
        // console.log(this.query)
      },  
      //重置筛选条件
      reset(){
        this.query.gardenFlag = '';
        this.query.gardenType = '';
        this.query.managementType = '';
        this.query.priceMax = '9999';
        this.query.priceMin = '';
      },
      // 获取参数
      getParams: function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return "";
      },
      // 判断浏览器类别
      IEVersion: function() {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
        var isIE =
          userAgent.indexOf("compatible") > -1 &&
          userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
        var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
        var isIE11 =
          userAgent.indexOf("Trident") > -1 &&
          userAgent.indexOf("rv:11.0") > -1;
        if (isIE) {
          var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
          reIE.test(userAgent);
          var fIEVersion = parseFloat(RegExp["$1"]);
          if (fIEVersion == 7) {
            return 7;
          } else if (fIEVersion == 8) {
            return 8;
          } else if (fIEVersion == 9) {
            return 9;
          } else if (fIEVersion == 10) {
            return 10;
          } else {
            return 6; //IE版本<=7
          }
        } else if (isEdge) {
          return "edge"; //edge
        } else if (isIE11) {
          return 11; //IE11
        } else {
          return -1; //不是ie浏览器
        }
      },
      // 获取cookie
      getCookie: function(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(";");
        for (var i = 0; i < ca.length; i++) {
          var c = ca[i].trim();
          if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
        }
        return "";
      },
      //获取图片路径
      getImgUrl: function() {
        var ip = window.location.host,
          url = "";
        if (ip.indexOf("127.0.0.1") >= 0 || ip.indexOf("localhost") >= 0) {
          url = "http://114.113.68.14:9000/image/";
        } else if (ip.indexOf("www.") >= 0) {
          url = "http://image.3dzhixuan.com/image/";
        } else {
          url = "http://" + ip + "/image/";
        }
        return url;
      },
      // 转化时间
      forDate: function(time) {
        var timestamp = (new Date(time.replace(/-/g, "/")) * 1) / 1000;
        function zeroize(num) {
          return (String(num).length == 1 ? "0" : "") + num;
        }
        var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
        var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数
        var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
        var tmDate = new Date(timestamp * 1000); // 参数时间戳转换成的日期对象

        var Y = tmDate.getFullYear(),
          m = tmDate.getMonth() + 1,
          d = tmDate.getDate();
        var H = tmDate.getHours(),
          i = tmDate.getMinutes(),
          s = tmDate.getSeconds();
        if (timestampDiff < 60) {
          // 一分钟以内
          return "刚刚";
        } else if (timestampDiff < 3600) {
          // 一小时前之内
          return Math.floor(timestampDiff / 60) + "分钟前";
        } else if (
          curDate.getFullYear() == Y &&
          curDate.getMonth() + 1 == m &&
          curDate.getDate() == d
        ) {
          return "今天" + zeroize(H) + ":" + zeroize(i);
        } else {
          var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
          if (
            newDate.getFullYear() == Y &&
            newDate.getMonth() + 1 == m &&
            newDate.getDate() == d
          ) {
            return "昨天" + zeroize(H) + ":" + zeroize(i);
          } else if (curDate.getFullYear() == Y) {
            return (
              zeroize(m) +
              "月" +
              zeroize(d) +
              "日 " +
              zeroize(H) +
              ":" +
              zeroize(i)
            );
          } else if (timestampDiff < 259200000) {
            return Math.floor(timestampDiff / 86400000) + "天前";
          } else {
            return (
              Y +
              "年" +
              zeroize(m) +
              "月" +
              zeroize(d) +
              "日 " +
              zeroize(H) +
              ":" +
              zeroize(i)
            );
          }
        }
      },
    }
  });
};
